﻿using System.Data.Entity;
using System.Linq;
using TavDom.Library.Core.Entities;
using TavDom.Library.Core.Utilities.Mapper;

namespace TavDom.Library.Core.Data.EntityFramework
{
    public class EfEntityRepositoryBase<TEntity> : IEntityRepository<TEntity> where TEntity : class, IEntity, new()
    {
        readonly DbContext _context;

        public EfEntityRepositoryBase(DbContext ctx)
        {
            _context = ctx;
        }

        public IQueryable<TEntity> GetAll()
        {
            _context.Configuration.ProxyCreationEnabled = false;
            return _context.Set<TEntity>();
        }

        public TEntity Get(TEntity entity)
        {
            return _context.Set<TEntity>().Find(entity.GetType().GetProperty("Id").GetValue(entity, null));
        }

        public TEntity Add(TEntity entity)
        {

            var addedEntity = _context.Set<TEntity>().Add(entity);
            _context.SaveChanges();
            return addedEntity;
        }

        public TEntity GetById(int id)
        {
            return _context.Set<TEntity>().Find(id);
        }

        public void Delete(TEntity entity)
        {
            var existingEntity = _context.Set<TEntity>().Find(entity.GetType().GetProperty("Id").GetValue(entity, null));
            _context.Set<TEntity>().Remove(existingEntity);
            _context.SaveChanges();
        }

        public TEntity Update(TEntity entity)
        {
            var existingEntity = _context.Set<TEntity>().Find(entity.GetType().GetProperty("Id").GetValue(entity, null));
            SimpleMapper.PropertyMap(entity, existingEntity);
            _context.SaveChanges();
            return existingEntity;
        }

    }
}
